package org.xiaojl.modules.sys.controller;

import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.xiaojl.common.base.BaseController;
import org.xiaojl.dwz.DwzAjax;
import org.xiaojl.modules.sys.entity.SysModule;
import org.xiaojl.modules.sys.entity.SysResource;
import org.xiaojl.modules.sys.service.SysModuleService;
import org.xiaojl.modules.sys.service.SysResourceService;
import org.xiaojl.utils.ToolUtil;

import com.baomidou.mybatisplus.mapper.EntityWrapper;

/**
 * <p>
 * 资源 前端控制器
 * </p>
 *
 * @author xiaojl
 * @since 2017-08-18
 */
@Controller
@RequestMapping("/sys/sysResource")
public class SysResourceController extends BaseController{
	private static final Logger log = LoggerFactory.getLogger(SysResourceController.class);
	private static final String basePagePath = "sys/resource/";
	@Autowired
	private SysResourceService sysResourceService;
	@Autowired
	private SysModuleService sysModuleService;
	
	@RequestMapping("/listBymodule")
	public ModelAndView listBymodule(Model model,Long pid){
		try {
			
			SysModule module = sysModuleService.selectById(pid);
			if(ToolUtil.isEmpty(module)){
				return operateError("ID=["+pid+"]的模块数据获取失败！");
			}
			model.addAttribute("module",module);
			
			String treeData = sysResourceService.selectAllResourceTree(pid);
			log.debug("获取到资源页面的treelist："+treeData);
			model.addAttribute("tree", treeData);
			
			//查询所有的模块列表
			List<SysModule> moduleList = sysModuleService.selectList(new EntityWrapper<SysModule>().orderBy("seq",true));
			model.addAttribute("moduleList", moduleList);
			
			return operatePage(basePagePath+"listByModule",model);
		} catch (Exception e) {
			log.error("查询列表数据出现异常:", e);
			return operateError("获取数据失败");
		}
	}
	
	/**
	 * 进入新菜单添加页面.
	 */
	@RequiresPermissions("sys/sysResource/add")
	@RequestMapping("/addUI")
	public ModelAndView addUI(SysResource resource, Model model, Long pid, String flag) {
		try {
			//flag=moduleId
			if ("moduleId".equals(flag)){
				SysModule sm = sysModuleService.selectById(pid);
				model.addAttribute("pid", pid);
				model.addAttribute("level",0);
				model.addAttribute("pName",sm.getName());
			}else{
				if(null != pid){
					SysResource pr = sysResourceService.selectById(pid);
					model.addAttribute("pName",pr.getName());
					model.addAttribute("pid",pr.getId());
					model.addAttribute("level",pr.getLevel());
				}
			}
			
			model.addAttribute("flag",flag);
			
			return operatePage(basePagePath+"add",model);
		} catch (Exception e) {
			log.error("查询数据出现异常:", e);
			return operateError("获取数据失败");
		}
	}
	
	/**
	 * 保存新增菜单.
	 */
	@RequiresPermissions("sys/sysResource/add")
	@RequestMapping("/add")
	public ModelAndView add(SysResource resource, DwzAjax dwz, String flag, Long pid, Integer level) {
		try {
			List<SysResource> list = sysResourceService.selectList(new EntityWrapper<SysResource>()
															.eq("name", resource.getName()).eq("type", "0"));
			if (list.size() > 0) {
				return operateError("菜单名称不能重复");
			}
			resource.setIsLeaf(0);//是叶子吗：0-是，1-不是
			
			if ("moduleId".equals(flag)){
				resource.setLevel(1);
				resource.setPid(pid);
			}else{
				if (ToolUtil.isNotEmpty(pid)) {
					SysResource p = sysResourceService.selectById(pid);
					if(ToolUtil.isEmpty(p)){
						return operateError("上级菜单不存在！");
					}else{
						//本资源类型为：菜单，需判断其上级是否具有按钮，如果有按钮则不可添加
						if(p.getIsLeaf()==2 && resource.getType()==0 ){
							return operateError("上级菜单下存在按钮资源，不可以再添加菜单资源！");
						}
					}
					resource.setLevel(level+1);
					resource.setPid(pid);
				}else{
					return operateError("请指定该菜单【所属模块】或者【上级菜单】");
				}
			}
			//级联添加
			sysResourceService.insertWithCacade(resource);
			
		} catch (Exception e) {
			// 记录系统操作日志
			log.error("新增资源出现异常:", e);
			return operateError("新增资源出错");
		}
		return operateSuccess(dwz);
	}
	
	/**
	 * 进入菜单修改页面.
	 */
	@RequiresPermissions("sys/sysResource/edit")
	@RequestMapping("/editUI")
	public ModelAndView editUI(Long id, Model model) {
		if (null != id) {
			SysResource resource = sysResourceService.selectById(id);
			long pid = resource.getPid();
			SysResource pr = sysResourceService.selectById(pid);
			if(ToolUtil.isNotEmpty(pr)){
				model.addAttribute("pName",pr.getName());
			}else{
				SysModule sm = sysModuleService.selectById(pid);
				model.addAttribute("pName",sm.getName());
				model.addAttribute("flag","moduleId");
			}
			
			model.addAttribute("resource",resource);
		}
		return operatePage(basePagePath+"edit",model);
	}
	
	/**
	 * 保存要修改的菜单.
	 * 
	 * @return
	 */
	@RequiresPermissions("sys/sysResource/edit")
	@RequestMapping("/edit")
	public ModelAndView edit(SysResource resource, DwzAjax dwz) {
		try {
			SysResource menu = sysResourceService.selectById(resource.getId());
			if (menu == null) {
				return operateError("无法获取要修改的数据");
			}
			
			sysResourceService.updateById(resource);
			// 记录系统操作日志
			return operateSuccess(dwz);
		} catch (Exception e) {
			// 记录系统操作日志
			log.error("更新资源信息出现异常:", e);
			return operateError("更新资源信息出错");
		}
	}
	
	/**
	 * 删除菜单.
	 */
	@RequiresPermissions("sys/sysResource/delete")
	@RequestMapping("/delete")
	public ModelAndView delete(Long id, DwzAjax dwz) {
		try {
			SysResource menu = sysResourceService.selectById(id);
			if (ToolUtil.isEmpty(menu)) {
				return operateError("无法获取要删除的数据");
			}

			// 先判断此菜单下是否有子菜单
			List<SysResource> childMenuList = sysResourceService.selectList(new EntityWrapper<SysResource>().eq("pid", id));
			if (childMenuList != null && !childMenuList.isEmpty()) {
				return operateError("此菜单下关联有【" + childMenuList.size() + "】个子菜单，不能支接删除!");
			}
			
			// 删除掉菜单
			sysResourceService.deleteWithCacade(menu);

			// 记录系统操作日志
			return operateSuccess(dwz);
		} catch (Exception e) {
			// 记录系统操作日志
			log.error("删除菜单出错:", e);
			return operateError("删除菜单出错");
		}
	}
}
